package glashart2xmltv;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.Arrays;
import java.util.List;
import java.util.Properties;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

/**
 * 
 * @author Jeroen Peschier
 * @version $Id: Config.java 2 2013-02-09 11:54:47Z peschierj@gmail.com $
 */
public class Config {

	private static final String CONFIG_DIR = ".glashart2xmltv";
	private static final String CONFIG_FILENAME = "config.properties";
	private static final Log log = LogFactory.getLog(Config.class);
	private static Config instance;
	private Properties props; 
	
	private Config() throws IOException {
		String homeDir = System.getProperty("user.dir");
		File configFile = new File(new File(homeDir, CONFIG_DIR), CONFIG_FILENAME);
		initialise(configFile);
	}
	
	private Config(String configFilename) throws IOException {
		File configFile = new File(configFilename);
		initialise(configFile);
	}
	
	private void initialise(File configFile) throws IOException {
		log.info("Attempting to load configuration from [" + configFile + "].");
		InputStream in = new FileInputStream(configFile);
		props = new Properties();
		props.load(in);
		in.close();
	}
	
	public static Config getInstance() {
		if (instance == null) {
			throw new IllegalStateException("Config not initialised!");
		}
		return instance;
	}
	
	public static synchronized Config initialise() throws IOException {
		instance = new Config();
		return instance;
	}
	
	public static synchronized Config initialise(String configDir) throws IOException {
		instance = new Config(configDir);
		return instance;
	}

	public File getOutputFile() {
		return new File(props.getProperty("outputFile"));
	}
	
	public String getBaseUrl() {
		return props.getProperty("baseUrl");
	}
	
	public int getNumberOfDays() {
		return Integer.parseInt(props.getProperty("numberOfDays"));
	}
	
	public List<String> getChannels() {
		String[] channels = props.getProperty("channels").split("\\s+");
		return Arrays.asList(channels);
	}
}